from flask import Flask,request,send_file,make_response
import json,os,threading,base64,requests
from ourapi import get_imgGeneral
from md5random import sjs;
app = Flask(__name__)

'''图像识别'''
@app.route("/file",methods=['POST'])
def upfile():
    '''接收文件'''
    params_file = request.files['file'];
    '''随机文件名'''
    dst = os.path.join(os.path.dirname(__file__),sjs()+params_file.name);
    '''保存文件'''
    params_file.save(dst)
    '''文件流变量'''
    cont = "";
    '''读取文件'''
    with open(dst, 'rb') as file:
        cont = file.read()
    '''删除文件'''
    os.remove(dst);
    '''获取表单数据type'''
    type=int(request.form['type'])
    '''返回识别结果'''
    return json.dumps(get_imgGeneral(type,cont));

'''获取图片'''
@app.route("/getImg",methods=['GET'])
def getImg():
    '''接收name参数'''
    ss = request.args['name']
    '''返回对应图片'''
    response = make_response(
        send_file("{}.png".format(ss)))
    '''定时任务函数，发送完数据后删除文件'''
    def sc():
        os.remove("{}.png".format(ss))

    '''定时任务，任务开启2秒后调用定时任务函数删除文件'''
    timer = threading.Timer(2, sc)
    '''任务开启'''
    timer.start()
    '''返回数据'''
    return response

'''图片转base64'''
@app.route("/toBe64",methods=['POST'])
def getB64():
    params_file = request.files['file'];
    dst = os.path.join(os.path.dirname(__file__), sjs() + params_file.name);
    params_file.save(dst)
    cont = "";
    with open(dst, 'rb') as file:
        cont = file.read()
    bas64D = base64.b64encode(cont)
    os.remove(dst);
    return bas64D

if __name__=='__main__':
        app.run(host='0.0.0.0',port=8087)
